package com.accounting.juanjuan.exception;

import java.util.HashMap;
import java.util.Map;

/**
 * 业务运行时异常，主要用于分类，对于所有的业务级异常，均继承该类
 * <p>禁止直接抛出该异常</p>
 */
public class BizRuntimeException extends RuntimeException {
    private static final long serialVersionUID = 5706097808191645829L;
    /**
     * 类别关键字
     */
    private static final String EXCEPTION_CATEGORY_NAME = "category";
    /**
     * 异常元数据
     */
    private final Map<String,String> metadata = new HashMap<>();

    public BizRuntimeException() {
        super();
        this.initExceptionType4Metadata();
    }

    public BizRuntimeException(String message) {
        super(message);
        this.initExceptionType4Metadata();
    }

    public BizRuntimeException(String message, Throwable cause) {
        super(message, cause);
        this.initExceptionType4Metadata();
    }

    public BizRuntimeException(Throwable cause) {
        super(cause);
        this.initExceptionType4Metadata();
    }

    protected BizRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.initExceptionType4Metadata();
    }

    /**
     * 返回元数据信息
     */
    public Map<String,String> getMetadata() {
        return this.metadata;
    }

    /**
     * 返回是否存在元数据
     */
    public boolean isMetadataEmpty() {
        return this.metadata.isEmpty();
    }

    /**
     * 放入元数据
     *
     * @param value 值
     */
    protected void putMetadata(String value) {
        this.metadata.put(BizRuntimeException.EXCEPTION_CATEGORY_NAME, value);
    }

    /**
     * 初始化异常类型
     */
    private void initExceptionType4Metadata() {
        this.putMetadata(this.getClass().getSimpleName().replace("Exception", ""));
    }
}
